package com.example.mybatisjpa.util;

import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

/**
 * @author Misty on 2020-12-03
 */
@Component
public final class SpringUtils implements BeanFactoryPostProcessor {
    private static ConfigurableListableBeanFactory BEAN_FACTORY;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        SpringUtils.BEAN_FACTORY = configurableListableBeanFactory;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) BEAN_FACTORY.getBean(name);
    }

    public static <T> T getBean(Class<T> cls) throws BeansException {
        return BEAN_FACTORY.getBean(cls);
    }

    public static boolean containsBean(String name) {
        return BEAN_FACTORY.containsBean(name);
    }

    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
        return BEAN_FACTORY.isSingleton(name);
    }

    public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
        return BEAN_FACTORY.getType(name);
    }

    public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
        return BEAN_FACTORY.getAliases(name);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getAopProxy(T invoker) {
        return (T) AopContext.currentProxy();
    }
}
